

import 'package:emojis/emoji.dart';

class EmojiUtil {
  static final RegExp REGEX_EMOJI = RegExp(r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d['
      r'\ud000-\udfff]|\ud83e[\ud000-\udfff])');
  
  static bool hasEmoji(String? str) {
    if (str == null) return false;
    return str.contains("￼e{") || str.contains("￼i{");
  }

  static bool hasEmoji2(String? str) {
    if (str == null) return false;
    return REGEX_EMOJI.firstMatch(str)?.group(0) != null;
  }

  static String replaceEmoji(String emojiStr) {
    String newString = emojiStr.replaceAllMapped(REGEX_EMOJI, (match) {
      String? group = match.group(0);
      if (group != null) {
        Emoji? emoji = Emoji.byChar(group);
        if (emoji != null) {
          String newStr = r"￼e{" + emoji.shortName + "}";
          return newStr;
        } else {
          return group;
        }
      }
      return "";
    });
    return newString;
  }

  static String replaceServerEmoji(String serverEmojiStr) {
    List<String> result = <String>[];
    String reg = "￼";
    List<String> strs = serverEmojiStr.split(reg);
    for(int i=0, lg=strs.length; i<lg; i++) {
      String emojiStr = strs[i];
      if (emojiStr.startsWith("e{") && emojiStr.endsWith("}")) {
        String emojiName = emojiStr.substring(2, emojiStr.length-1);
        Emoji? emoji = Emoji.byShortName(emojiName);
        if (emoji != null) {
          result.add(emoji.char);
        }
      } else {
        result.add(emojiStr);
      }
    }
    return result.join();
  }

  static String? _parseServerEmoji(String str) {
    if (str.startsWith("￼e{") && str.endsWith("}")) {
      String emojiName = str.substring(3, str.length-1);
      Emoji? emoji = Emoji.byName(emojiName);
      return emoji?.char;
    }
    return null;
  }
}
